function hex2Bytes(hex) {   //string转hex
    let pos = 0;
    let len = hex.length;
    if (len % 2 !== 0) {
        return null;
    }
    len /= 2;
    const hexA = [];
    for (let i = 0; i < len; i++) {
        let s = hex.substr(pos, 2);
        let v = parseInt(s, 16);
        if (v >= 127) v = v - 255 - 1
        hexA.push(v);
        pos += 2;
    }
    return hexA;
}

function bytes2HexStr(arrBytes) {
    let str = "";
    for (let i = 0; i < arrBytes.length; i++) {
        let tmp;
        let num = arrBytes[i];
        if (num < 0) {
            //此处填坑，当byte因为符合位导致数值为负时候，需要对数据进行处理
            tmp = (255 + num + 1).toString(16);
        } else {
            tmp = num.toString(16);
        }
        if (tmp.length === 1) {
            tmp = "0" + tmp;
        }
        str += tmp;
    }
    return str;
}

function bytes2Str(array) { return String.fromCharCode.apply(String, array); }

function str2Bytes(str) {
    const bytes = [];
    let len, c;
    len = str.length;
    for(let i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if(c >= 0x010000 && c <= 0x10FFFF) {
            bytes.push(((c >> 18) & 0x07) | 0xF0);
            bytes.push(((c >> 12) & 0x3F) | 0x80);
            bytes.push(((c >> 6) & 0x3F) | 0x80);
            bytes.push((c & 0x3F) | 0x80);
        } else if(c >= 0x000800 && c <= 0x00FFFF) {
            bytes.push(((c >> 12) & 0x0F) | 0xE0);
            bytes.push(((c >> 6) & 0x3F) | 0x80);
            bytes.push((c & 0x3F) | 0x80);
        } else if(c >= 0x000080 && c <= 0x0007FF) {
            bytes.push(((c >> 6) & 0x1F) | 0xC0);
            bytes.push((c & 0x3F) | 0x80);
        } else {
            bytes.push(c & 0xFF);
        }
    }
    return bytes;
}

module.exports = {
    hex2Bytes,
    bytes2HexStr,
    bytes2Str,
    str2Bytes
}